package com.peng.mybatis_framework.config.config_entity_property;

import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

public class DynamicPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer implements InitializingBean{

	private static final String envParamName = "env.model";
	
	private Map<String,DynamicConfigSetting> dynamicConfigSettingMap;
	
	private String defaultEnvModel;
	
	public Map<String, DynamicConfigSetting> getDynamicConfigSettingMap() {
		return dynamicConfigSettingMap;
	}

	public void setDynamicConfigSettingMap(Map<String, DynamicConfigSetting> dynamicConfigSettingMap) {
		this.dynamicConfigSettingMap = dynamicConfigSettingMap;
	}

	public String getDefaultEnvModel() {
		return defaultEnvModel;
	}

	public void setDefaultEnvModel(String defaultEnvModel) {
		this.defaultEnvModel = defaultEnvModel;
	}

	public static String getEnvparamname() {
		return envParamName;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(dynamicConfigSettingMap == null) {
			throw new RuntimeException();
		}
		
		//获取运行参数
		String envModel = System.getProperty(envParamName);
		if(StringUtils.isEmpty(envModel)) {
			envModel = defaultEnvModel;
			System.out.println("使用默认运行参数");
		}
		System.out.println("获取运行时参数:"+envModel);
		DynamicConfigSetting dynamicConfigSetting = dynamicConfigSettingMap.get(envModel);
		if(dynamicConfigSetting == null) {
			throw new RuntimeException("未找到与运行时相关的配置");
		}
		Resource[] propertyFileLocations = dynamicConfigSetting.getPropertyFileLocations();
		
		if(propertyFileLocations != null) {
			this.setLocations(propertyFileLocations);
		}else {
			throw new RuntimeException("propertyFileLocaitons is null");
		}
	}

}
